<template>
  <div class="login-body">
    <div class="bg"></div>
    <div class="login-panel">
      <el-form
          ref="formDataRef"
          :model="formData"
          class="login-from"
          :rules="rules"
      >
        <div class="login-title">EasyJob管理后台</div>
        <el-form-item prop="phone">
          <el-input
              v-model.trim="formData.phone"
              placeholder="请输入手机号"
              clearable
              size="large"
          >
            <template #prefix>
              <span class="iconfont icon-phone"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              type="password"
              show-password
              v-model.trim="formData.password"
              placeholder="请输入密码"
              clearable
              size="large"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkCode">
          <div class="check-code-panel">
            <el-input
                v-model.trim="formData.checkCode"
                placeholder="请输入验证码"
                clearable
                size="large"
                @keyup.enter.native="login"
            >
              <template #prefix>
                <span class="iconfont icon-checkCode"></span>
              </template>
            </el-input>
            <img
                :src="checkCodeUrl"
                class="check-code"
                @click="changeCheckCode"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              class="login-button"
              size="large"
              @click="login"
          >登录
          </el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {nextTick, ref, onMounted, getCurrentInstance} from "vue";
import {useRouter} from "vue-router";
import md5 from "js-md5";

const {proxy} = getCurrentInstance();
const router = useRouter();
const api = {
  checkCode: "/api/checkCode",
  login: "/login",
};

const formData = ref({
  phone: "",
  password: "",
  checkCode: "",
  rememberMe: false,
});

const formDataRef = ref();
const rules = {
  phone: [{required: true, message: "请输入手机号"}],
  password: [{required: true, message: "请输入密码"}],
  checkCode: [{required: true, message: "请输入验证码"}],
};

// 验证码
const checkCodeUrl = ref(null);
const changeCheckCode = () => {
  checkCodeUrl.value = `${api.checkCode}?time=${new Date().getTime()}`;
};

const login = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {};
    Object.assign(params, formData.value);
    // 判断密码是否加密
    const cookieLoginInfo = proxy.VueCookies.get("loginInfo");
    console.log(cookieLoginInfo);
    if (!cookieLoginInfo || params.password !== cookieLoginInfo.password) {
      params.password = md5(params.password);
    }

    let result = await proxy.Request({
      url: api.login,
      params,
      // 登录失败刷新验证码
      errorCallback: () => {
        formData.value.checkCode = ""
        changeCheckCode();
      },
    });
    if (!result) {
      return;
    }
    // 记住密码，存在cookies中
    if (params.rememberMe) {
      const loginInfo = {
        phone: params.phone,
        password: params.password,
        rememberMe: params.rememberMe,
      };
      proxy.VueCookies.set("loginInfo", loginInfo, "7d");
    } else {
      proxy.VueCookies.remove("loginInfo");
    }

    proxy.Message.success("登录成功");
    sessionStorage.setItem("userInfo", JSON.stringify(result.data));

    // 跳转页面
    let firstMenu = result.data.menuList[0];
    if (firstMenu.children.length > 0) {
      firstMenu = firstMenu.children[0];
    }
    router.push(firstMenu.menuUrl);
  });
};

// 初始化方法
onMounted(() => {
  init();
  // 判断 cookies 中是否有登录信息
  const cookieLoginInfo = proxy.VueCookies.get("loginInfo");
  if (cookieLoginInfo) {
    formData.value = cookieLoginInfo;
  }
});
const init = () => {
  nextTick(() => {
    changeCheckCode();
  });
};
</script>

<style lang="scss">
.login-body {
  height: 100vh;
  display: flex;
  background: #23b9f1;

  .bg {
    flex: 1;
    background-image: url("../assets/login-bg2.webp");
    background-size: 800px;
    background-repeat: no-repeat;
    background-position: center;
  }

  .login-panel {
    margin: 0 15% 8% 0;
    display: flex;
    align-items: center;
    justify-content: center;

    .login-from {
      background: #fff;
      padding: 20px;
      border-radius: 5px;
      width: 400px;

      .login-title {
        text-align: center;
        font-size: 18px;
        padding: 5px 0 15px;
        font-weight: bold;
      }

      .check-code-panel {
        display: flex;

        .check-code {
          margin-left: 10px;
          cursor: pointer;
        }
      }

      .login-button {
        width: 100%;
      }
    }
  }
}
</style>
